package com.stadium.service.impl;

import java.time.temporal.Temporal;
import java.util.*;

import com.stadium.common.utils.CommonUtils;
import com.stadium.common.utils.SqlMapper;
import com.stadium.common.utils.UserUtils;
import com.stadium.dto.*;
import com.stadium.entity.GameTeam;
import com.stadium.entity.REventTeam;
import com.stadium.entity.RTeamUser;
import com.stadium.entity.TeamRecord;
import com.stadium.mapper.GameScheduleMP;
import com.stadium.mapper.GameTeamMP;
import com.stadium.mapper.REventTeamMP;
import com.stadium.mapper.RTeamUserMP;
import com.stadium.service.GameTeamSV;
import com.stadium.service.SysUserSV;
import com.stadium.vo.GameTeamVo;
import com.stadium.vo.SysUserVo;
import com.stadium.vo.TeamLogVo;
import com.stadium.vo.searchVo.GameScheduleSearchVo;
import com.stadium.vo.searchVo.GameTeamSearchVo;
import com.stadium.vo.searchVo.RTeamUserSearchVo;
import com.stadium.vo.searchVo.TeamLogSearchVo;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;

@Service
@Transactional
public class GameTeamSVI implements GameTeamSV {
    @Autowired
    private GameTeamMP mapper;
    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    private RTeamUserMP rTeamUserMP;
    @Autowired
    private SysUserSV sysUserSV;
    @Autowired
    private REventTeamMP rEventTeamMP;
    @Autowired
    private GameScheduleMP gameScheduleMP;
    @Autowired
    private TeamLogSVI teamLogSVI;

    @Override
    public List<GameTeam> queryBySQL(String sql, Map<String, Object> map) {
        return sqlMapper.selectList(sql, map, GameTeam.class);
    }

    @Override
    public void save(GameTeamVo gameTeamVo) {
        GameTeam gameTeam = new GameTeam();
        BeanUtils.copyProperties(gameTeamVo, gameTeam);
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        gameTeam.setCreateUser(UserUtils.getUserId());
        gameTeam.setUpdateUser(UserUtils.getUserId());
        gameTeam.setId(id);
        int number = mapper.getMaxNumber();
        String format = String.format("%06d", ++number);
        gameTeam.setNumber(format);
        mapper.save(gameTeam);
        TeamLogVo teamLogVo = new TeamLogVo();
        teamLogVo.setContent("球队成立");
        teamLogVo.setArea(gameTeamVo.getArea());
        teamLogVo.setTeamId(id);
        teamLogSVI.save(teamLogVo);
    }

    @Override
    public void update(GameTeamVo gameTeamVo) {
        GameTeam gameTeam = new GameTeam();
        BeanUtils.copyProperties(gameTeamVo, gameTeam);
        gameTeam.setUpdateUser(UserUtils.getUserId());
        if (StringUtils.isNotEmpty(gameTeamVo.getUserId())) {
            GameTeamDto gameTeamDto = mapper.get(gameTeamVo.getId());
            if (!gameTeamDto.getUserId().equals(gameTeamVo.getUserId())) {
                SysUserVo sysUserVo = new SysUserVo();
                sysUserVo.setId(gameTeamVo.getUserId());
                sysUserVo.setRole("1");
                sysUserSV.update(sysUserVo);
                sysUserVo.setId(gameTeamDto.getUserId());
                sysUserVo.setRole("2");
                sysUserSV.update(sysUserVo);
            }
        }
        mapper.update(gameTeam);
    }

    @Override
    public void saveBatch(List<GameTeam> list) {
        mapper.saveBatch(list);
    }

    @Override
    public void delete(String id) {
        mapper.delete(id);
    }

    @Override
    public void deleteBatch(String[] ids) {
        mapper.deleteBatch(ids);
    }

    @Override
    public List<GameTeamDto> query(GameTeamSearchVo searchVo) {
        List<GameTeamDto> gameTeamDtoList = mapper.query(searchVo);
        for (GameTeamDto gameTeamDto : gameTeamDtoList) {
            RTeamUserSearchVo rTeamUserSearchVo = new RTeamUserSearchVo();
            rTeamUserSearchVo.setTeamId(gameTeamDto.getId());
            int total = rTeamUserMP.getCount(rTeamUserSearchVo);
            gameTeamDto.setPalyerNum(total);
        }
        return gameTeamDtoList;
    }

    @Override
    public GameTeamDto get(String id) {
        List<Map<String, String>> sysUserDtoList = rTeamUserMP.queryByTeamId(id);
        GameTeamDto gameTeamDto = mapper.get(id);
        gameTeamDto.setSysUserList(sysUserDtoList);
        return gameTeamDto;
    }

    @Override
    public int getCount(GameTeamSearchVo searchVo) {
        return mapper.getCount(searchVo);
    }

    @Override
    public List<GameTeamDto> queryByUserId(GameTeamSearchVo searchVo) {
        return mapper.query(searchVo);
    }

    @Override
    public void adminPassOnTo(String teamId, String userId) {
        GameTeam gameTeam = new GameTeam();
        gameTeam.setUpdateUser(UserUtils.getUserId());
        GameTeamDto gameTeamDto = mapper.get(teamId);
        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setId(userId);
        sysUserVo.setRole("1");
        sysUserSV.update(sysUserVo);
        sysUserVo.setId(gameTeamDto.getUserId());
        sysUserVo.setRole("2");
        sysUserSV.update(sysUserVo);
        mapper.update(gameTeam);
    }

    @Override
    public List<GameEventWithScheduleDto> queryEventsByTeamId(String teamId) {
        List<GameEventDto> gameEventDtoList = rEventTeamMP.findListByTeamId(teamId);
        List<GameEventWithScheduleDto> gameEventWithScheduleDtoList  =new ArrayList<>();
        GameScheduleSearchVo gameScheduleSearchVo = new GameScheduleSearchVo();
        gameEventDtoList.stream().forEach(gameEventDto -> {
            GameEventWithScheduleDto gameEventWithScheduleDto = new GameEventWithScheduleDto();
            if (gameEventDto.getRegistrationStarttime().getTime() > new Date().getTime()) {
                gameEventDto.setStatus("未开始报名");
            }
            if(belongCalendar(new Date(),gameEventDto.getRegistrationStarttime(),gameEventDto.getRegistrationEndtime())){
                gameEventDto.setStatus("报名中");
            }
            if(belongCalendar(new Date(),gameEventDto.getRegistrationEndtime(),gameEventDto.getCompetitionEndtime())){
                gameEventDto.setStatus("进行中");
            }
            if(gameEventDto.getCompetitionEndtime().getTime() < new Date().getTime()){
                gameEventDto.setStatus("已结束");
            }
            BeanUtils.copyProperties(gameEventDto,gameEventWithScheduleDto);
            gameScheduleSearchVo.setEventId(gameEventDto.getId());
            gameScheduleSearchVo.setTeamId(teamId);
            List<GameScheduleDto> gameScheduleDtoList = gameScheduleMP.query(gameScheduleSearchVo);
            if (gameScheduleDtoList != null) {
                gameEventWithScheduleDto.setScheduleDtoList(gameScheduleDtoList);
            }
            gameEventWithScheduleDtoList.add(gameEventWithScheduleDto);
        });
        return gameEventWithScheduleDtoList;
    }

    @Override
    public List<TeamAndEventDto> getListByUserId(String userId) {
        GameTeamSearchVo gameTeamSearchVo = new GameTeamSearchVo();
        gameTeamSearchVo.setUserId(userId);
        List<GameTeamDto> gameTeamDtoList = mapper.queryByPlayerUserId(gameTeamSearchVo);
        if(gameTeamDtoList != null || gameTeamDtoList.size() > 0 ){
            List<TeamAndEventDto> teamAndEventDtoList = new ArrayList<>(gameTeamDtoList.size());
            gameTeamDtoList.stream().forEach(gameTeamDto -> {
                TeamAndEventDto teamAndEventDto = new TeamAndEventDto();
                BeanUtils.copyProperties(gameTeamDto, teamAndEventDto);
                RTeamUserSearchVo rTeamUserSearchVo = new RTeamUserSearchVo();
                rTeamUserSearchVo.setTeamId(gameTeamDto.getId());
                int total = rTeamUserMP.getCount(rTeamUserSearchVo);
                teamAndEventDto.setPalyerNum(total);

                List<GameEventDto> gameEventDtoList = rEventTeamMP.findListByTeamId(gameTeamDto.getId());
                Iterator<GameEventDto> iterator = gameEventDtoList.iterator();
                while(iterator.hasNext()){
                    GameEventDto gameEventDto = iterator.next();
                    Date  competitionEndtime=gameEventDto.getCompetitionEndtime();
                    if(competitionEndtime.getTime() < new Date().getTime()){
                        iterator.remove();
                    }
                    if (gameEventDto.getRegistrationStarttime().getTime() > new Date().getTime()) {
                        gameEventDto.setStatus("未开始报名");
                    }
                    if(belongCalendar(new Date(),gameEventDto.getRegistrationStarttime(),gameEventDto.getRegistrationEndtime())){
                        gameEventDto.setStatus("报名中");
                    }
                    if(belongCalendar(new Date(),gameEventDto.getRegistrationEndtime(),gameEventDto.getCompetitionEndtime())){
                        gameEventDto.setStatus("进行中");
                    }
                }
                teamAndEventDto.setGameEventDtoList(gameEventDtoList);
                teamAndEventDtoList.add(teamAndEventDto);
            });

            return teamAndEventDtoList;
        }else {
            return new ArrayList<>(0);
        }
    }

    @Override
    public List<TeamLogDto> TeamLog(String teamId) {
        TeamLogSearchVo teamLogSearchVo = new TeamLogSearchVo();
        teamLogSearchVo.setTeamId(teamId);
        return teamLogSVI.query(teamLogSearchVo);
    }

    @Override
    public TeamRecord TeamRecord(String teamId) {
        TeamRecord teamRecord = mapper.teamRecorg(teamId);
        GameScheduleSearchVo gameScheduleSearchVo = new GameScheduleSearchVo();
        gameScheduleSearchVo.setTeamId(teamId);
        int total = gameScheduleMP.getCount(gameScheduleSearchVo);
        teamRecord.setTotal(total);
        return teamRecord;
    }

    /**
     * 判断时间是否在时间段内
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

}
